import {
  CallHandler,
  ExecutionContext,
  HttpStatus,
  Injectable,
  NestInterceptor,
  StreamableFile,
} from '@nestjs/common';
import { Observable, map } from 'rxjs';

@Injectable()
export class TransformResponseInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const response = context.switchToHttp().getResponse();
    if (response.statusCode === HttpStatus.CREATED) {
      response.statusCode = HttpStatus.OK;
    }
    return next.handle().pipe(
      map((data: any) => {
        if (
          !(data instanceof Error) &&
          typeof data === 'object' &&
          !(data instanceof StreamableFile)
        ) {
          return {
            code: data.code || '000000',
            data: data.data,
            msg: data.message || data.msg || 'success',
          };
        } else {
          return data;
        }
      }),
    );
  }
}
